203. 移除链表元素
为保证权益,题目请参考 203. 移除链表元素(From LeetCode).
解决方案1
Python
python
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
if head is None:
return head
t = head
while t is not None and t.val == val:
t = t.next
if t is None:
return None
before = t
head = t
t = t.next
while t is not None:
if t.val == val:
before.next = t.next
t = t.next
else:
t = t.next
before = before.next
return head
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31